// src/app.ts
import fastify, { FastifyInstance } from 'fastify';
import fastifyCors from "@fastify/cors";
import { env } from './utils/env';
import logger from './common/logger';
import errorHandler from './error/errorHandler';

// 声明 Fastify 实例类型
const app: FastifyInstance = fastify({
  logger: env.NODE_ENV !== 'production',
});

// 按顺序注册模块
app.register(logger);     // 强类型日志
app.register(errorHandler); // 类型化异常处理
app.register(fastifyCors, {
    credentials: false,
    origin: ['*'],
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['*']
})

// 启动服务（异步安全）
const start = async () => {
  try {
    const port = Number(env.PORT)
    await app.listen({ port: port, host: env.HOST });
    app.log.info(`🚀 API 运行在 http://localhost:${env.PORT}`);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();